package com.crm.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import org.apache.commons.httpclient.NameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.crm.sys.model.TokenPackage;
 

public class testcall {
	
	
	
    private static final String charset = "utf-8";
    private static final String url = "https://ccc.aliyun.com/open/DownloadRecording.do";
    private static String json = "{\"instanceId\":\"d0920c2d-804d-4959-b45b-8341006cdf2a\",\"fileName\":\"152721158314400080310502.wav\"}";
public static void main(String[] args) {
	
/*	String ss="{\"code\":\"OK\",\"recordings\":[{\"fileDescription\":\"20180525092623-陈先生\",\"duration\":0,\"fileName\":\"152721158314400080310502.wav\",\"agentId\":\"217612526436755977\",\"contactId\":\"2012934297\",\"agentName\":\"陈先生\",\"callingNumber\":\"80310502\",\"contactType\":\"Outbound\",\"startTime\":1527211583000,\"calledNumber\":\"18948354468\"}],\"requestId\":\"BF86D8C4-D8DF-4AC5-B58B-0EBEDEB6F709\",\"success\":true,\"httpStatusCode\":200}";
	Recordings recordings = JSONObject.parseObject(ss, Recordings.class);
	System.out.println(recordings);*/
	try {
		   String request ="{\"ContactId\":'2012934297',\"instanceId\":\"d0920c2d-804d-4959-b45b-8341006cdf2a\"}";
		
		   String tokeen =  refreshAccessToken("/api/cc/auth");
		   System.out.println(tokeen);
		   
		   TokenPackage   tokenPackage =  TokenPackage.parse(tokeen);
		   
	        String ss =	CrmUtil.invokeApiByBearerToken(tokenPackage.getAccessToken(), "DownloadRecording", json) ;
	        Map maps = (Map)JSON.parse(ss);    
	        boolean b =    (boolean)maps.get("success");
	        if(b) {
	        	JSONObject  jsonObj = 	(JSONObject)maps.get("mediaDownloadParam");
	           String fileUrl= (String) jsonObj.get("signatureUrl");
	           String fileName = (String) jsonObj.get("fileName");
	              // Map fileMap = (Map)JSON.parse();    
	           
	              File sss = CommonUtil.downLoadFromUrl(fileUrl.replace("\"",""),   fileName,"d:/uc/");  
	           
	              try {  
	                  System.out.println(   CommonUtil.getAudioTime(sss) + " s" );
	              } catch(Exception e) {  
	                  e.printStackTrace();  
	              }  
	              
	        
	               //signatureUrl
	               //fileName
	        }
	    
		    //    String json = "{\"instanceId\":\"" + instanceId + "\",\"fileName\":\"" + fileName + "\"}";
		      /*  CloseableHttpClient httpclient = HttpClients.createDefault();
		        HttpPost post = new HttpPost(url);
		        Header header = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
		        post.setHeader(header);
		        // 创建参数队列
		        List<BasicNameValuePair> formparams = new ArrayList<>();
		        formparams.add(new BasicNameValuePair("accessKeySecret", secret));
		        formparams.add(new BasicNameValuePair("accessKeyId", key));
		        formparams.add(new BasicNameValuePair("securityToken", token));
		        formparams.add(new BasicNameValuePair("request", json));
		        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, charset);
		        post.setEntity(urlEncodedFormEntity);
		        CloseableHttpResponse response = httpclient.execute(post);
		        HttpEntity entity = response.getEntity();
		        InputStream content = entity.getContent();
		        FileOutputStream out = new FileOutputStream(new File("D:\\ut", "3.wav"));
		        int i = -1;
		        while ((i = content.read()) != -1) {
		            out.write(i);
		        }
		        content.close();
		        out.close();*/
		 
	
	}catch(Exception e) {
		e.printStackTrace();
	}
	
	 
	
}



private static String refreshAccessToken( String requestUrl) throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("client_id","4470473126604100500"));
    params.add(new NameValuePair("grant_type", "refresh_token"));
    params.add(new NameValuePair("client_secret", "Z9N0ddGP4zcUYO3vYe6y32Jea1ccf1msUYrgyLfjlO3s3rLMtPObJIfvRdGZCODc"));
    params.add(new NameValuePair("refresh_token", "ptV2xYO2wmkygYnw "));
    params.add(new NameValuePair("redirect_uri", requestUrl));

    NameValuePair[] pairs = new NameValuePair[params.size()];

    return HttpRequester.post("http://oauth.aliyun.com/v1/token", params.toArray(pairs));
}



static	String key = "LTAIPoBv8iZWNwWW";
static  String secret = "Ov0k9pSSxKTu0krSA6kLiTsCS6Zy1Z";
static  String token = "eyJhbGciOiJSUzI1NiIsImsyaWQiOiJlNE92NnVOUDhsMEY2RmVUMVhvek5wb1NBcVZLblNGRyIsImtpZCI6IkpDOXd4enJocUowZ3RhQ0V0MlFMVWZldkVVSXdsdEZodWk0TzFiaDY3dFUifQ.cU9xL2xUTElzclpGU1RISmFLMFloMldzNW45cFBOSWdNRGNxQmVHZmZTbjZVOEFoMXhUZDVTcm13SE9LcHBiZkorUGdvclgySC8xSTZHcldmQ1hNVlE5aU4zQ0FRam80dU0rUVFKdDFSY2V0bmFQcml5WFljTDhmNUZ2c1pFd3BhTDFOajVvRW9QVG83S1NVU3JpTFdKQmNnVHB1U094cUd4cGpCeE9XTFpTWnNOUDdzRkp4RTVlSFNzUm1Oa0FKV0poUFovdXY2Z2NRd2lHQTdYSk1uUGFKU1BiSWhyQVFWYXFYODJDM2d3PT0.P6Gn0Ud6myBAShWMwpf_SFyDAFwnV04iyjLJTvNy9G-afqsTeN5mPgAFlDZyUeI7QthtpSulCEcFqsFKCWQYkA7fs8UBaxijANQAi-ReH8_t3thIifUagKAWc8wARVBKlLHnMeVsCNaCeEG3RJUw-WBuhf1VDIE_7yNhu0_G2qhPfK40vRYX3lAyAK2dJV6fr08uJXvy3fopZeKi94AX1SpOzjL7WxgGDW0uOR4fgErd0p_zgGQaQKSsK1pjUxygR0ZT6Tx58jhkJzJKzHL7fMdTb0nU80jtEGV45EP3-61H4FJB0xIFaaYXi7z7FUi2EIjd61fzywNPvlTKvyiCvg.bkhUclhJYm1McDJFalBLZ2dZMll1MldzNW45cFBOSWdNRGNxQmVHZmZTbjZVOEFoMXhUZDVTcm13SE9LcHBiZkorUGdvclgySC8xSTZHcldmQ1hNVlE5aU4zQ0FRam80dU0rUVFKdDFSY2V0bmFQcml5WFljTDhmNUZ2c1pFd3BhTDFOajVvRW9QVG83S1NVU3JpTFdKQmNnVHB1U094cUd4cGpCeE9XTHB5VnN0Ny9zRkp4RTVlSFNzUm1Oa0FKV0poUFovdXY2Z2NRd2lHQTdYSk1uUGFKU1BiSWhyQVFWcUtRKzIyemd3PT0.fpP9dMyrnfYqwJV7R1Bvp2EjmY-zbB00khp55jSM0arxAdRcxA2mfs8CocuGZNHnNBjzQFA6PCdaXenz2yYiUm_CUqUoKHRMPPRw5aLm738ZTWB8HawZ6MIwPcAp_-UJhJXVHKyLdXekNAHGXqghtSuAxhwFcviGw4MFJr-R5Y0cGJzbbbdDg_YKgDy0qlPpZmppHpCjhR0DWbu5SNtfSxlPlfMhmVhRhL1L7wavwIbvtaFa9KdPUeFfoLRhgMb1TT_n0B4eYp6XadVQYpuZdViHTEtdmRkvNyLP5Y_IbKkTaCpf_MYH8Hx7pgbAgk0JQFTuIUXWXh26jrtdjRnh_A";

public static DefaultAcsClient getClient() {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("CCC", "ccc.cn-shanghai.aliyuncs.com");
    IClientProfile stsProfile = DefaultProfile.getProfile("cn-shanghai", map, key,secret, token);
    DefaultAcsClient stsClient = new DefaultAcsClient(stsProfile);
    stsClient.setAutoRetry(false);
    return stsClient;
}
	
	
	
	
	
	
	
	
    /**
     * 用来生成nonce字符串，长度必须是45位
     */
    private final static RandomString randomString = new RandomString(45);
	public static void mainddddd(String[] args) throws UnsupportedEncodingException {
		
			 
			/*String state = UUID.randomUUID().toString();
    String nonce = randomString.nextString();
    //storeStateInSession(httpServletRequest.getSession(), state, nonce);
     String ss =   "https://signin.aliyun.com/oauth2/v1/auth?response_type=code&response_mode=form_post"
            + "&redirect_uri=" + URLEncoder.encode("http://127.0.0.1:8081/auth/callback", "UTF-8")
            + "&client_id=4470473126604100500" 
            + "&state=" + state
            + "&codeChallenge=" + nonce
            + "&access_type=offline";
    // https://signin.aliyun.com/oauth2/v1/auth?response_type=code&response_mode=form_post&redirect_uri=https://127.0.0.1:8443/aliyun/auth/callback&client_id=120171021&state=75fb39a2-8b9f-49d6-9888-57a20ce8d7e5&codeChallenge=NTZ4wOaGVacs3oIk1sLfh8QWsF7CBfqTOEt3Sm1QJtzP3
       System.out.println(ss);*/
		String token ="{\"request_id\":\"a65cf61b-0320-4d3b-ae7a-fc5b3a2e2202\",\"access_token\":\"eyJhbGciOiJSUzI1NiIsImsyaWQiOiJlNE92NnVOUDhsMEY2RmVUMVhvek5wb1NBcVZLblNGRyIsImtpZCI6IkpDOXd4enJocUowZ3RhQ0V0MlFMVWZldkVVSXdsdEZodWk0TzFiaDY3dFUifQ.M2xDUU1wU2dmcDA2OE9yNHJvc3hqR1dzNW45cFBOSWdNRGNxQmVHZmZTbjZVOEFoMXhUZDVTcm13SE9LcHBiZkorUGdvclgySC8xSTZHcldmQ1hNVlE5aU4zQ0FRam80dU0rUVFKdDFSY2V0bmFQcml5WFljTDhmNUZ2c1pFd3BhTDFOajVvRW9QVG83S1NVU3JpTFdKQmNnVHB1U094cUd4cGpCeE9YS0oyWXZ0NytzRkp4RTVlSFNzUm1Oa0FKV0poUFovdXY2Z2NRd2lHQTdYSk1uUGFKU1BiSWhyQVJVS09VOFcyeWd3PT0.PUH3A8ATtR9S_d-j0k47ePfvUOmrQA_nziCGmIBaDWpShfqeJCMi5pcOUP2BF_8HUYHzCTGDTDDZeP1ChF4bMsKe1RKBsrxrVPuvCMvKMqfflLsPh5s3b1Ox1ZgMFJfItPEBblZ6_UDGHEH-O4WZhUoXngJi0g5yzIdfvgiLpyn7g9kvyl1uIksI3U-nTIbtXuK07ZvoT6-yc2b8mZQ4VRs0cwXVkAlEJDC39ddQ0pZT70BAFUHV5XuYZNeR78A3BWMhRsIiJM0IjxMTjA81JeZ123KaQNX7DJKFsBme18Jo3GkITLZCiitdPwqBywGEWhBcZb0UJu651PviQnhT0w\",\"token_type\":\"Bearer\",\"refresh_token\":\"h8Dexvc9al1uwJFk\",\"id_token\":\"eyJraWQiOiJKQzl3eHpyaHFKMGd0YUNFdDJRTFVmZXZFVUl3bHRGaHVpNE8xYmg2N3RVIiwiYWxnIjoiUlMyNTYifQ.eyJhdWQiOiI0NDcwNDczMTI2NjA0MTAwNTAwIiwic3ViIjoiMjE3NjEyNTI2NDM2NzU1OTc3IiwidXBuIjoiY2hlbkAxODEwMzI2MzcxMjE5NDI4Lm9uYWxpeXVuLmNvbSIsImlzcyI6Imh0dHBzOlwvXC9vYXV0aC5hbGl5dW4uY29tIiwibmFtZSI6ImNoZW5AMTgxMDMyNjM3MTIxOTQyOC5vbmFsaXl1bi5jb20iLCJleHAiOjE1MjY2OTg5OTUsImJpZCI6IjI2ODQyIiwiaWF0IjoxNTI2Njk1Mzk1LCJhaWQiOiIxODEwMzI2MzcxMjE5NDI4In0.h-wz46H8t2zgn2LW-JK8Bpzpe2K1GlYg0u6LoxxhTBNtbZe_IHtyQKp02WFVgVYkRSds_txJKiCQYDqu99gVJ4kznneeIdgfpQ3SEiVIMLVI52RxBThXxwf1gSx4TSVQwQ5dr7MNbYz21U0d-X7pkVxg7wNqO_Jnxc3DVv2CE0sOOkWs4j58okwFgfcY5xgKsiKFl2cmtSWbQAz62P5ExXfU5BjccgwQt2-YqbzhinAfA69nuimeC8EtxG86RkS186JzycJAz1lAQrnjhFmauV0ormmGr3TlLdea_tiNcPdaLSn5lE_mC0HmOnM38ruDnTNhgzE_UwTwWXkI1_uf8g\",\"additional_information\":{\"refresh_token_id\":31165},\"expires_in\":\"3599\"}";
        TokenPackage tokenPackage = JSONObject.parseObject(token, TokenPackage.class);
        
        System.out.println(tokenPackage);
	}
}
